# -*- coding:utf-8 -*-
"""
" ip2region python seacher client module
"
" Autho: koma<komazhang@foxmail.com>
" Date : 2015-11-06
"""
from __future__ import unicode_literals
import struct, sys, os, time
from platform import python_version

from ip2Region import Ip2Region

from flask import Flask
from flask import request
from flask import jsonify
import rwjson
import urllib.parse

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False


@app.route('/')
def hello_world():
    rst ='<div style="align-items: center;width: 100%;text-align: center;font-size: 24px;"><p>access <a href="https://xn--15t.top/" style="color: #00AAFF;text-decoration: none;">心.top</a>for more messages.</p><br><p>./js or ./json is for retrun visiter data <a href="https://gitee.com/xyxywan/ip-and-region">learn more</a></p><br><p>./js_record is for record visiters data <a href="https://gitee.com/xyxywan/visitors-record">learn more</a></p></div>'
    return rst

@app.route("/json", methods=["GET"])
def ipjson():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    dict1 = testSearch(ip)
    dict2 = {'ip': ip}
    dnew = Merge(dict2, dict1)
    # to_str = str(dnew)
    print(dnew)
    return jsonify(dnew), 200


@app.route("/js", methods=["GET"])
def ipjs():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    dict1 = testSearch(ip)
    dict2 = {'ip': ip}
    dnew = Merge(dict2, dict1)
    # to_str = str(dnew)
    strrr = "var ip_data =" + str(dnew)
    return strrr, 200

@app.route("/js_record", methods=["GET"])
def js_record():
    strrr = 'var params=Object.keys(ip_data).map(function(key){return key+"="+ip_data[key]}).join("&");var d=new Date();var mt=String(d.getMinutes());var now_date="&date="+d.getFullYear()+"·"+d.getMonth()+"·"+d.getDate()+"·"+d.getHours()+":"+(mt.length>1?mt:mt.replace(/(.{0})/,"$10"));	window.onload=function(){var div = document.createElement("div"); var divattr = document.createAttribute("id");divattr.value = "visiter";  div.setAttributeNode(divattr); var divattrsty = document.createAttribute("style");  divattrsty.value = "position: fixed;border:1px solid red;bottom: 0;color: #00AAFF;left: 0;font-size: 24px;text-align: center;font-family: 仿宋;" ; div.setAttributeNode(divattrsty);document.getElementsByTagName("body").item(0).appendChild(div); var script3=document.createElement("script");script3.setAttribute("type","text/javascript");script3.setAttribute("src","http://42.192.91.114:10746/record/"+String(params)+now_date);document.head.appendChild(script3);script3.onload=script3.onreadystatechange=function(){if(!this.readyState||this.readyState=="loaded"||this.readyState=="complete"){document.getElementById("visiter").innerHTML="访客数量:"+visiter_data.total_people+"<br>"+"总访问量:"+visiter_data.total_times;}}}'
    return strrr, 200

@app.route('/record/<data>')
def user_info(data):
    print("recive data : "+data)
    n_data ="?"+str(data)
    url_change = urllib.parse.urlparse(n_data)  # 将url拆分为6个部分

    query = url_change.query  # 取出拆分后6个部分中的查询模块query

    lst_query = urllib.parse.parse_qsl(query)  # 使用parse_qsl返回列表
    dict1 = dict(lst_query)  # 将返回的列表转换为字典
    dict_query = urllib.parse.parse_qs(query)  # 使用parse_qs返回字典
    #print("使用parse_qsl返回列表  ：", lst_query)
    #print("将返回的列表转换为字典   ：", dict1)
    dict2 = rwjson.main_process_json(dict1)
    print("return data :", dict2)
    strr_rt ="var visiter_data ="+str(dict2)
    return strr_rt

def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res


def testSearch(resvip):
    """
    " ip2region test function
    """
    argLen = len(sys.argv)
    version = python_version()
    algorithms = ["binary", "b-tree", "memory"]

    if argLen < 2:
        print("Usage: python testSearcher.py [ip2region db file] [alrogrithm]")
        print("Algorithm: %s" % ", ".join(algorithms))
        return 0

    dbFile = sys.argv[1]

    if (not os.path.isfile(dbFile)) or (not os.path.exists(dbFile)):
        print("[Error]: Specified db file is not exists.")
        return 0

    if argLen > 2:
        algorithm = sys.argv[2]
    try:
        algorithms.index(algorithm)
    except Exception as e:
        algorithm = "b-tree"

    print("initializing %s..." % (algorithm))
    print("+----------------------------------+")
    print("| ip2region test program           |")
    print("+----------------------------------+")

    searcher = Ip2Region(dbFile)

    while True:
        if version[:1] == "2":
            line = raw_input("ip2region>> ")
        else:
            print("ip2region>> ")
            line = resvip
        line = line.strip()

        if line == "":
            print("[Error]: Invalid ip address.")
            continue

        if line == "quit":
            print("[Info]: Thanks for your use, Bye.")
            break

        if not searcher.isip(line):
            print("[Error]: Invalid ip address.")
            continue

        try:
            sTime = time.time() * 1000
            if algorithm == "binary":
                data = searcher.binarySearch(line)
            elif algorithm == "memory":
                data = searcher.memorySearch(line)
            else:
                data = searcher.btreeSearch(line)
            eTime = time.time() * 1000
            print("%s|%s in %5f millseconds" % (data["city_id"], data["region"].decode('utf-8'), eTime - sTime))
            result = data["region"].decode('utf-8')
            resultARR = result.split("|")
            returnARR1 = ["Country", "Province", "city", "isp"]
            returnARR2 = [resultARR[0], resultARR[2], resultARR[3], resultARR[4]]
            returnDICT = dict(zip(returnARR1, returnARR2))
            print(returnDICT)
            return returnDICT

        except Exception as e:
            print("[Error]: %s" % e)

    searcher.close()


if __name__ == "__main__":
    app.run(
        host="10.0.4.4",
        port=int("10746")
    )
